﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace InternshipManagement.Models
{
    public class DocumentRepository
    {
        public InternshipEntities entities = new InternshipEntities();

        public IQueryable<Document> FindAllDocuments()
        {
            return entities.Documents.Where(d=>d.UpdateDate != null).OrderByDescending(d=>d.UpdateDate);
        }

        public Document GetDocument(int ID)
        {
            return entities.Documents.FirstOrDefault(d => d.ID == ID);
        }

        public void AddDocument(Document document)
        {
            entities.Documents.AddObject(document);
        }
        public void DeleteDocument(Document document)
        {
            entities.Documents.DeleteObject(document);
        }

        public string uploadDocument(HttpPostedFileBase document)
        {
            if (document != null && document.ContentLength > 0)
            {
                string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/Documents"), Path.GetFileName(document.FileName));
                document.SaveAs(filePath);
                return "/App_Data/Documents/" + Path.GetFileName(document.FileName);
            }
            return null;
        }

        public int? saveDocument(HttpPostedFileBase document,string Name)
        {
            if (document != null && document.ContentLength > 0)
            {
                string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/Documents"), Path.GetFileName(document.FileName));
                document.SaveAs(filePath);
                Document doc = new Document();
                doc.Path = "/App_Data/Documents/" + Path.GetFileName(document.FileName);
                doc.Name = Name ?? Path.GetFileName(document.FileName);
                entities.Documents.AddObject(doc);
                entities.SaveChanges();
                return doc.ID;
            }
            return null;
        }


        //
        // Persistence
        public void Save()
        {
            entities.SaveChanges();
        }
    }
}
